import { TextWidget } from '@inbiz/react';
import { Empty, Spin } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import AppList from '../../../FunPermission/components/Permission/List';
import TreeList from '../../../FunPermission/components/Permission/Tree';
import {
  addButtonUserPerm,
  delButtonUserPerm,
  getButtonUserPerm,
  getMenuTree,
  getOnlineTree,
} from '../../../service';
import '../../../style.less';

function Action(props) {
  const { appList, selectMember, permConfig, containerHeight } = props;
  const { MemberId, MemberType } = selectMember;
  const [outId, $outId] = useState(appList[0]?.OutId); // 应用Id
  const [selectedTreeKeys, $selectedTreeKeys] = useState([]); // 菜单Id
  const [treeList, $treeList] = useState([]); //菜单列表
  const [menuList, $menuList] = useState([]); //选中菜单按钮
  const [permList, $permList] = useState([]); //权限列表
  const [loadding1, $loadding1] = useState(false); //菜单加载
  const [loadding2, $loadding2] = useState(false); //动作加载
  const [loadding3, $loadding3] = useState(false); //子页面加载
  const [childrenList, $childrenList] = useState([]); //子页面列表
  const [selectChildrenPage, $selectChildrenPage] = useState([]); //选中子页面

  // 站点点击，获取对应的菜单
  useEffect(() => {
    getMenuTreeFun();
  }, [outId, MemberId]);

  // 菜单数据change，初始化选中节点
  useEffect(() => {
    if (treeList?.length) {
      $selectedTreeKeys([treeList[0]?.OutId]);
    }
  }, []);

  // 加载选中菜单配置
  useEffect(() => {
    $permList([]);
    $menuList([]);
    $selectChildrenPage([]);
    if (selectedTreeKeys[0]) {
      getChildrenPage(selectedTreeKeys[0]);
    }
  }, [selectedTreeKeys]);

  // 加载选中页面配置
  useEffect(() => {
    $permList([]);
    $menuList([]);
    if (selectChildrenPage[0]) {
      getMenuRelationTree(selectChildrenPage[0]);
    }
  }, [selectChildrenPage]);

  // 获取子页面
  const getChildrenPage = (menueId) => {
    if (outId) {
      $loadding3(true);
      // dispatch({
      //   type: 'permissionFun/getOnlineTree',
      //   payload: {
      //     siteOutId: outId,
      //     menuOutId: menueId,
      //     type: 100,
      //   },
      // }).then(res => {
      //   $loadding3(false)
      //   if (!res) {
      //     $childrenList(null);
      //     $selectChildrenPage([])
      //     return;
      //   }
      //   $selectChildrenPage([res?.[0]?.Id])
      //   $childrenList(formateRelationTree(res, true));
      // })
      const payload = {
        siteOutId: outId,
        menuOutId: menueId,
        type: 100,
      };
      getOnlineTree(payload).then((res) => {
        $loadding3(false);
        if (!res) {
          $childrenList(null);
          $selectChildrenPage([]);
          return;
        }
        $selectChildrenPage([res?.[0]?.Id]);
        $childrenList(formateRelationTree(res, true));
      });
    }
  };
  // 第一级id  接口传参时过滤掉  一级目录不允许编辑权限
  const parentIds = useMemo(() => {
    if (menuList.length) {
      return menuList.map((item) => item.Id);
    } else {
      return [];
    }
  }, [menuList]);

  const clearData = () => {
    $permList([]);
    $treeList([]);
    $menuList([]);
    $childrenList([]);
  };

  // 获取菜单列表
  const getMenuTreeFun = () => {
    clearData();
    $loadding1(true);
    // $loadding2(true)
    if (outId) {
      // dispatch({
      //   type: 'permissionFun/getMenuTree',
      //   payload: {
      //     siteOutId: outId,
      //     parentOutId: '',
      //   },
      // }).then(res => {
      //   $loadding1(false)
      //   $loadding2(false)
      //   if (!res) {

      //     return;
      //   }
      //   $treeList(res);
      //   $selectedTreeKeys([res[0]?.OutId]);
      // })
      const payload = {
        siteOutId: outId,
        parentOutId: '',
      };
      getMenuTree(payload).then((res) => {
        $loadding1(false);
        $loadding2(false);
        if (!res) {
          return;
        }
        $treeList(res);
        $selectedTreeKeys([res[0]?.OutId]);
      });
    }
  };
  // 异步加载菜单
  const onLoadData = (treeNode) => {
    return new Promise<void>((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      //获取菜单
      // dispatch({
      //   type: 'permissionFun/getChildMenuTree',
      //   payload: {
      //     siteOutId: outId,
      //     parentOutId: treeNode.props.dataRef.OutId,
      //   },
      //   callback: res => {
      //     treeNode.props.dataRef.children = res;
      //     $treeList(updateTreeData(treeList, res, treeNode.props.eventKey))
      //     resolve();
      //   },
      // });
      const payload = {
        siteOutId: outId,
        parentOutId: treeNode.props.dataRef.OutId,
      };
      getMenuTree(payload).then((res) => {
        treeNode.props.dataRef.children = res;
        $treeList(updateTreeData(treeList, res, treeNode.props.eventKey));
        resolve();
      });
    });
  };
  const updateTreeData = (list, children, key) => {
    return list.map((node) => {
      if (node.OutId === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });
  };

  //获取角色菜单动作权限
  const getMenuRelationTree = (pageOutId, isEdit?) => {
    $loadding2(true);
    if (outId && MemberId) {
      // dispatch({
      //   type: 'permissionFun/getButtonUserPerm',
      //   payload: {
      //     siteOutId: outId,
      //     menuOutId: selectedTreeKeys[0],
      //     memberId: MemberId,
      //     memberType: MemberType,
      //     pageOutId,
      //   },
      // }).then(res => {
      //   $loadding2(false)
      //   if (!res) {
      //     return;
      //   }
      //   $permList((origin) => {
      //     if (isEdit) {
      //       return [...getPermList(res)]
      //     } else {
      //       return [...origin, ...getPermList(res)]
      //     }
      //   })
      //   $menuList(formateRelationTree(res))

      // })
      const payload = {
        siteOutId: outId,
        menuOutId: selectedTreeKeys[0],
        memberId: MemberId,
        memberType: MemberType,
        pageOutId,
      };
      getButtonUserPerm(payload).then((res) => {
        $loadding2(false);
        if (!res) {
          return;
        }
        $permList((origin) => {
          if (isEdit) {
            return [...getPermList(res)];
          } else {
            return [...origin, ...getPermList(res)];
          }
        });
        $menuList(formateRelationTree(res));
      });
    }
  };
  //格式化菜单动作数据
  const formateRelationTree = (data, selectable?) => {
    data.forEach((item) => {
      item.Name = item.ObjectName;
      item.OutId = item.Id;
      item.children = item.Children?.length ? formateRelationTree(item.Children) : null;
      item.isLeaf = item.Children?.length ? false : true;
      item.selectable = selectable ? selectable : false;
      item.checkable = item.Children?.length ? false : true;
      item.disableCheckbox = !item?.ParentId ? (item.Children?.length ? false : true) : false;
    });
    return data;
  };
  // 获取有权限的列表
  const getPermList = (list) => {
    let permList: any = [];
    list.forEach((item) => {
      if (item.PermissionValue != 0 && item.ParentId) {
        permList.push(item.Id);
      }
      if (item.Children?.length) {
        permList = [...permList, ...getPermList(item.Children)];
      }
    });
    return permList;
  };

  const onCheck = (checkedKeys, e) => {
    let newCheckedKeys: any = [];
    checkedKeys.map((item) => {
      if (parentIds.indexOf(item) == -1) {
        newCheckedKeys.push(item);
      }
    });
    if (e.checked) {
      // 添加权限
      changePerm('add', newCheckedKeys);
    } else {
      //删除权限
      changePerm('del', newCheckedKeys);
    }
  };
  // 编辑权限
  const changePerm = (type: string, checkedKeys: any) => {
    let payload: any = {
      siteOutId: outId,
      memberType: MemberType,
      memberId: MemberId,
      menuOutId: selectedTreeKeys[0],
      pageOutId: selectChildrenPage[0],
    };
    let menuFuncButtonPermList: any[] = [];
    if (type == 'add') {
      checkedKeys.forEach((item) => {
        if (permList.indexOf(item) == -1)
          menuFuncButtonPermList.push({
            entityId: item,
            permissionValue: 4,
          });
      });
      payload.menuFuncButtonPermList = menuFuncButtonPermList;
    } else {
      permList.forEach((item) => {
        if (checkedKeys.indexOf(item) == -1) menuFuncButtonPermList.push(item);
      });
      payload.permissionIds = findpremIds(menuFuncButtonPermList, menuList);
    }
    // dispatch({
    //   type: type == 'add' ? 'permissionFun/addButtonUserPerm' : 'permissionFun/delButtonUserPerm',
    //   payload,
    // }).then(res => {
    //   const old = permList;
    //   getMenuRelationTree(selectChildrenPage[0], true)
    //   if (!res) {
    //     $permList(origin => {
    //       return [...old]
    //     })
    //   }
    // })
    permRequst(type == 'add' ? addButtonUserPerm : delButtonUserPerm, payload);
  };
  // 权限更改请求
  const permRequst = (service: any, payload: any) => {
    service(payload).then((res) => {
      const old = permList;
      getMenuRelationTree(selectChildrenPage[0], true);
      if (!res) {
        $permList((origin) => {
          return [...old];
        });
      }
    });
  };

  // 通过outId查找对应权限值
  const findpremIds = (outIds, list) => {
    let temp = [];
    list.forEach((menu) => {
      outIds.forEach((outId) => {
        if (menu.OutId == outId && menu.ParentId) {
          temp.push(menu.PermissionId);
        }
      });
      if (menu.children?.length) {
        temp = [...temp, ...findpremIds(outIds, menu.children)];
      }
    });
    return temp;
  };

  // 判断是否是ifream嵌套
  const isIframe = useMemo(() => {
    return location?.hash?.indexOf('permissionFun') != -1;
  }, []);

  return (
    <div className={'main'} style={{ height: `calc(${containerHeight} - 144px)` }}>
      <div className={'appList'}>
        <AppList
          outId={outId}
          appClick={(res) => {
            $outId(res);
          }}
          list={appList}
        />
      </div>

      <div className={'treeList'}>
        {treeList.length ? (
          <TreeList
            key={`${MemberId}${outId}`}
            list={treeList}
            onLoadData={onLoadData}
            selectedKeys={selectedTreeKeys}
            treeClick={(arr) => $selectedTreeKeys(arr)}
          />
        ) : loadding1 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
      <div className={'treeList'}>
        {childrenList.length ? (
          <TreeList
            key={outId}
            list={childrenList}
            // onLoadData={onLoadData}
            selectedKeys={selectChildrenPage}
            treeClick={(arr) => {
              console.log(arr);
              $selectChildrenPage(arr);
            }}
          />
        ) : loadding3 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
      <div className={'lastTreeList'}>
        {menuList.length ? (
          <TreeList
            key={`${MemberId}${outId}`}
            list={menuList}
            checkable={true}
            checkedKeys={permList}
            // checkStrictly={true}
            treeCheck={onCheck}
          />
        ) : loadding2 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
    </div>
  );
}

export default Action;
